﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "serial.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , settings(new QSettings("YourCompany", "YourApp"))
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 设置背景图片
    QFile file(":/ship.png"); // 如果使用资源系统，请根据实际情况调整路径
    if(file.exists()) {
        this->setStyleSheet("MainWindow { background-image: url(:/ship.png)};");
    } else
    {
        qDebug() << "Background image not found!";
    }
    //隐匿密码
    ui->password->setEchoMode(QLineEdit::Password);
    //登录按钮
    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::login);
    //按钮传参显示密码按钮
    connect(ui->radioButton, &QPushButton::clicked, this, &MainWindow::display_psd);
    // 记住密码复选框
    connect(ui->checkBox, &QCheckBox::stateChanged, this, &MainWindow::saveSettings);
    loadSettings();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete settings;
}


void MainWindow::login()
{
    saveSettings();
    QString nameString = ui->accout->text();
    QString pswdString = ui->password->text();

    // 检查用户名和密码是否匹配
    if ((nameString == QString::fromLocal8Bit("admin") && pswdString == QString::fromLocal8Bit("123456")) ||
            (nameString == QString::fromLocal8Bit("user") && pswdString == QString::fromLocal8Bit("111111"))) {
        Serial* w = new Serial(); // 使用 'this' 作为父对象，Qt 会自动管理其生命周期
        qDebug() << "Creating Software instance.";
        this->close();
        w->show();
    } else
    {
        QMessageBox::about(this, "警告", "用户名或密码错误");
    }
}

void MainWindow::display_psd(bool checked)
{
    if (checked) {
        //显示密码
        ui->password->setEchoMode(QLineEdit::Normal);
    }
    else {
        //密文显示
        ui->password->setEchoMode(QLineEdit::Password);
    }
}

void MainWindow::saveSettings()
{
    bool remember = ui->checkBox->isChecked();
    QString username = ui->accout->text();
    QString password = ui->password->text();

    settings->setValue("remember", remember);
    if (remember) {
        settings->setValue("username", username);
        settings->setValue("password", password);
    } else {
        settings->remove("username");
        settings->remove("password");
    }
}
void MainWindow::loadSettings()
{
    bool remember = settings->value("remember", false).toBool();
    QString username = settings->value("username", "").toString();
    QString password = settings->value("password", "").toString();

    ui->checkBox->setChecked(remember);
    ui->accout->setText(username);
    ui->password->setText(password);
}
